#include <iostream>
#include <string>
#include <map>
#include <ctime>
#include "ais/ais.h"
#include "ais/decode_body.h"
using namespace std;

int main()
{
	std::map<unsigned int, std::map<std::string,std::string> > cache;
	std::map<unsigned int, time_t > cache_time;
	while(1)
	{
		std::string str;
		cin >> str;
		if (str.size()<6)
			continue;
		std::string header = str.substr(1,4);
		if (header!="AIVD" && header!="BSVD")
			continue;
		const int pad = libais::GetPad(str);
		const std::string strBody = libais::GetBody(str);
		std::unique_ptr<libais::AisMsg> msg = libais::CreateAisMsg(strBody,pad);
		if (!msg)
		{
			cout<<"#AIS Message 0=\""<<str<<"\":\n";
			cout<<"Error String\n";
			continue;
		}
		cout<<"#AIS Message "<<msg->message_id<<"=\""<<str<<"\":\n";

		std::map<std::string ,std::string> map_values = msg->values();
		for(auto p:map_values)
		{
			cout<<p.first<<"="<<p.second<<";";
		}
		cout<<"\n";
		if (map_values.find("mmsi")!=map_values.end())
		{
			unsigned int mmsi = atoi(map_values["mmsi"].c_str());
			if (mmsi>0)
			{
				std::map<std::string,std::string> & currData = cache[mmsi];
				cache_time[mmsi] = time(0);
				for (auto p:map_values)
					currData[p.first] = p.second;
				if (currData.find("position_lat")!=currData.end() && currData.find("position_lon")!=currData.end())
				{
					fprintf(stderr,"source=ais;destin=geomarker;function=update_icon;icon=ais;name=ais%u;lat=%s;lon=%s;rotate=%s;smooth=1;\n",
							mmsi, currData["position_lat"].c_str(), currData["position_lon"].c_str(), currData["cog"].c_str());
					fprintf(stderr,"source=ais;destin=geomarker;function=update_props;name=ais%u;LABEL=%u;",mmsi, mmsi);
					for(auto p:currData)
					{
						fprintf(stderr,"%s=%s;",p.first.c_str(),p.second.c_str());
					}
					fprintf(stderr,"\n");
				}
			}

		}
		std::vector<unsigned int> delist;
		for(auto p:cache_time)
		{
			if (p.second + 300 < time(0))
				delist.push_back(p.first);
		}
		for (unsigned int v:delist)
		{
			fprintf(stderr,"source=ais;destin=geomarker;function=delete_marks;name0=ais%u;\n",v);
			cache.erase(v);
			cache_time.erase(v);
		}

	}
	return 0;
}
